package com.itheima.train.common.service.impl;

import cn.hutool.json.JSONObject;
import com.itheima.train.common.domain.Log;
import com.itheima.train.common.mapper.LogMapper;
import com.itheima.train.common.service.LogService;
import com.itheima.train.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Liang
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@RequiredArgsConstructor
@Slf4j
public class LogServiceImpl implements LogService {
    private final LogMapper logMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String username, String browser, String ip, String requestMethod, ProceedingJoinPoint joinPoint, Log logs) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.itheima.train.common.anno.Log aopLog = method.getAnnotation(com.itheima.train.common.anno.Log.class);
        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        if (argValues != null) {
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
            if (null == username || username.trim().length() == 0) {
                try {
                    username = new JSONObject(argValues[0]).get("username").toString();
                } catch (Exception ignored) {
                }
            }
        }
        // 描述
        logs.setDescription(aopLog.value());
        logs.setRequestIp(ip);
        logs.setAddress(StringUtils.getCityInfo(ip));
        logs.setMethod(methodName);
        logs.setUsername(username == null ? ip : username);
        logs.setLocalIp(StringUtils.getLocalIp());
        String s = params.toString();
        if (s.length() >= 10000) {
            s = s.substring(0, 10000);
        }
        logs.setBrowser(browser);
        logs.setParams(s + "}");
        logs.setCreateTime(new Date());
        logMapper.save(logs);
    }
}
